<template>
	<view class="container">
		<!-- 页面头部 -->
		<view class="header">
			<view class="header-logo">
				<sl-image :value="avatar" mode="aspectFit"></sl-image>
			</view>
		</view>
		<!-- 表单 -->
		<view class="fetch-user" v-if="!bind">
			<view class="login-form">
				<!-- 手机号 -->
				<view class="form-item">
					<input class="form-item--input" type="number" v-model="mobile" maxlength="11"
						placeholder="请输入手机号码" />
				</view>
				<!-- 图形验证码 -->
				<view class="form-item">
					<input class="form-item--input" type="text" v-model="captchaCode" maxlength="5"
						placeholder="请输入图形验证码" />
					<view class="form-item--parts">
						<view class="captcha" @click="getCaptcha()">
							<image class="image" :src="showCaptcha"></image>
						</view>
					</view>
				</view>
				<!-- 短信验证码 -->
				<view class="form-item">
					<input class="form-item--input" type="number" v-model="smsCode" maxlength="6"
						placeholder="请输入短信验证码" />
					<view class="form-item--parts flex-middle-center">
						<view class="captcha-sms" @click="handelSmsCaptcha()">
							<text v-if="!smsState" class="activate">获取验证码</text>
							<text v-else class="un-activate">重新发送({{ times }})秒</text>
						</view>
					</view>
				</view>
				<!-- 登录按钮 -->
				<view class="login-button" @click="handleLogin">
					<text>登录</text>
				</view>
			</view>
			<!-- 底部 -->
			<view class="footer">
				<text class="other">其他登陆方式</text>
				<view class="login-type" @click="wxLogin">
					<image class="custom-icon iconfont-size-big" src="../../static/icon-a-weixin1.svg"></image>
				</view>
				<view class="footer-text">
					<text>
						未注册的手机号，验证后会自动创建星橘账号，登陆即代表您同意《用户隐私政策》
					</text>
				</view>
			</view>
		</view>
		<view class="bind-phone" v-else>
			<view class="auth-title">申请获取以下权限</view>
			<view class="auth-subtitle">获得你的手机号</view>
			<view class="no-login-btn">
				<button class="button btn-normal" @click="onEmitSuccess">绑定其他手机号</button>
			</view>
		</view>
	</view>
</template>

<script>
	import Constants from '@/constants';
	import VerifyApi from '@/api/user/verify';
	import CaptchaApi from '@/api/user/captcha'
	import LoginApi from '@/api/user/login'
	import store from '@/store'
	import * as Verify from '@/utils/verify'
	import {
		tabBarPages
	} from '../../../plugins/app.ext.js';
	//倒计时时长(秒)
	const times = 60
	//表单验证场景
	const GET_CAPTCHA = 10
	const SUBMIT_LOGIN = 20
	//app登陆组件
	//@group 业务登陆组件
	export default {
		name: 'appPlus',
		//
		mixins: [Constants],
		//
		props: {
			//第三方用户信息数据
			login: {
				type: Object,
				default () {
					return {};
				}
			}
		},
		//
		data() {
			return {
				//正在加载
				isLoading: false,
				//图形验证码信息
				captcha: {},
				//图形验证码
				captchaCode: '',
				//短信验证码发送状态
				smsState: false,
				//倒计时
				times,
				//手机号
				mobile: '',
				//短信验证码信息
				smsCodeKey: '',
				//短信验证码
				smsCode: '',
				//绑定手机号
				bind: false,
				//授权信息
				oauth: null,
			}
		},
		//
		computed: {
			showCaptcha: function() {
				if (this.captcha && this.captcha.base64) {
					return 'data:image/png;base64,' + this.captcha.base64;
				}
				return '';
			}
		},
		//
		mounted() {
			//获取图形验证码
			this.getCaptcha()
		},
		//
		methods: {
			//获取图形验证码
			getCaptcha() {
				const app = this
				CaptchaApi.simple().then(result => app.captcha = result.obj || {})
			},
			//点击发送短信验证码
			handelSmsCaptcha() {
				const app = this
				if (!app.isLoading && !app.smsState && app.formValidation(GET_CAPTCHA)) {
					app.sendSmsCaptcha()
				}
			},
			//表单验证
			formValidation(scene = GET_CAPTCHA) {
				const app = this
				//验证获取短信验证码
				if (scene === GET_CAPTCHA) {
					if (!app.validteMobile(app.mobile) || !app.validteCaptchaCode(app.captchaCode)) {
						return false
					}
				}
				//验证提交登录
				if (scene === SUBMIT_LOGIN) {
					if (!app.validteMobile(app.mobile) || !app.validteSmsCode(app.smsCode)) {
						return false
					}
				}
				return true
			},
			//验证手机号
			validteMobile(str) {
				if (Verify.isEmpty(str)) {
					this.$app.toast('请先输入手机号')
					return false
				}
				if (!Verify.isMobile(str)) {
					this.$app.toast('请输入正确格式的手机号')
					return false
				}
				return true
			},
			//验证图形验证码
			validteCaptchaCode(str) {
				if (Verify.isEmpty(str)) {
					this.$app.toast('请先输入图形验证码')
					return false
				}
				return true
			},
			//验证短信验证码
			validteSmsCode(str) {
				if (Verify.isEmpty(str)) {
					this.$app.toast('请先输入短信验证码')
					return false
				}
				return true
			},
			//请求发送短信验证码接口
			sendSmsCaptcha() {
				const app = this
				app.isLoading = true
				VerifyApi.login({
						phone: app.mobile,
						captcha: app.captchaCode
					}, app.captcha.token)
					.then(res => {
						if (res.success) {
							// 保存短信验证码的信息
							app.smsCodeKey = res.obj.key;
							// 显示发送成功
							app.$app.toast('发送成功！')
							// 执行定时器
							app.timer()
						} else if (res.code === 30001) {
							app.$app.error('图形验证码错误！')
						} else {
							app.$app.error(res.msg || '发送验证码错误，请重试！')
						}
					}).finally(() => app.isLoading = false)
			},
			//执行定时器
			timer() {
				const app = this
				app.smsState = true
				const inter = setInterval(() => {
					app.times = app.times - 1
					if (app.times <= 0) {
						app.smsState = false
						app.times = times
						clearInterval(inter)
					}
				}, 1000)
			},
			//点击登录
			handleLogin() {
				const app = this
				if (!app.isLoading && app.formValidation(SUBMIT_LOGIN)) {
					app.submitLogin()
				}
			},
			//确认登录
			submitLogin() {
				const app = this
				app.isLoading = true
				let login = {
					name: app.login.name || '',
					headimg: app.login.headimg || '',
					phone: app.mobile,
					smsCode: app.smsCode,
					appId: app.login.appId || '',
					openId: app.login.openId || '',
					unionId: app.login.unionId || '',
					account: app.login.account || 'UserName'
				}
				store.dispatch('Login', {
					smsCodeKey: app.smsCodeKey,
					login
				}).then(result => {
					//显示登录成功
					app.$app.toast('登陆成功')
					//跳转回原页面
					setTimeout(() => {
						app.onNavigateBack(1)
					}, 1000)
				}).catch((err) => {
					app.$app.error(err.msg)
				}).finally(() => app.isLoading = false)
			},
			//微信授权登陆
			wxLogin() {
				const app = this
				uni.login({
					provider: 'weixin',
					timeout: 5000,
					success(res) {
						console.log('res: ', res);
						//
						uni.getUserInfo({
							provider: 'weixin',
							withCredentials: true,
							lang: 'zh_CN',
							timeout: 5000,
							success(res) {
								const userInfo = res.userInfo
								console.log('userInfo: ', userInfo);
								store.dispatch('AppWxLogin', {
									appId: 'wx8dd7ca8c336afadc',
									openId: userInfo.openId,
									unionId: userInfo.unionId,
									nickname: userInfo.nickName,
									headimgurl: userInfo.avatarUrl,
								}).then(result => {
									//
									app.$app.toast('登录成功')
									// 跳转回原页面
									setTimeout(() => {
										app.onNavigateBack()
									}, 1000)
								}).catch(oauth => {
									console.log('oauth：', oauth)
									// 如果授权成功，但是还没有注册
									if (oauth && oauth.openId) {
										app.bind = true;
										app.oauth = oauth;
									}
									// 授权错误
									else {
										// 一键登录成功
										app.$app.error('授权失败，请重新授权！')
									}
								})
							}
						})
					}
				})
			},
			// 获取手机号
			getPhoneNumber(e) {
				let detail = e.detail;
				console.log('获取手机号', detail)
				if (detail && detail.errMsg == 'getPhoneNumber:ok') {
					this.onBindSuccess(detail);
				} else {
					// 如果获取失败则让用户填写手机号
					this.onEmitSuccess();
				}
			},

			// 获取手机号成功
			onBindSuccess(detail) {
				let app = this;
				LoginApi.mpResolvePhone({
						sessionKey: app.oauth.sessionKey,
						encryptedData: detail.encryptedData,
						iv: detail.iv
					})
					.then(res => {
						if (res.success) {
							let login = {
								name: '', // app.userInfo.nickName, // 这个名称："微信用户"，所以不传， 后台判空处理
								headimg: '', // app.userInfo.avatarUrl, // 这个数据不能访问，所以不传
								phone: res.obj.purePhoneNumber,
								appId: app.oauth.appId,
								openId: app.oauth.openId,
								unionId: app.oauth.unionId || '',
								account: 'MpWeixin'
							}
							app.doLogin(login)
						} else {
							app.$app.error('授权失败，请重新授权！')
						}
					}).catch(() => {
						app.$app.error('授权失败，请重新授权！')
					})
			},
			/**
			 * 授权成功，但是需要获取用户的手机号
			 */
			onEmitSuccess: function() {
				this.$emit('success', {
					name: this.oauth.nickname,
					headimg: this.oauth.headimgurl,
					phone: '',
					appId: this.oauth.appId,
					openId: this.oauth.openId,
					unionId: this.oauth.unionId || '',
					account: 'AppWeixin'
				})
			},
			// wxLogin: async function() {
			// 	const app = this;
			// 	try {
			// 		const {
			// 			code
			// 		} = await uni.login({
			// 			provider: 'weixin',
			// 			// timeout: 5000,
			// 		});
			// 		console.log('code: ', code);
			// 		const {
			// 			userInfo
			// 		} = await uni.getUserInfo({
			// 			provider: 'weixin',
			// 			withCredentials: true,
			// 			lang: 'zh_CN',
			// 			timeout: 5000,
			// 		});
			// 		console.log('userInfo: ', userInfo);
			// await store.dispatch('AppWxLogin', {
			// 	appId: '',
			// 	openId: userInfo.openid,
			// 	unionId: userInfo.unionld,
			// 	nickname: userInfo.nickName,
			// 	headimgurl: userInfo.avatarUrl,
			// });
			// 		app.$app.toast('登录成功');
			// 		setTimeout(() => {
			// 			app.onNavigateBack();
			// 		}, 1000);
			// 	} catch (error) {
			// 		console.log('error:', error);
			// 		if (error && error.openId) {
			// 			app.bind = true;
			// 			app.oauth = error;
			// 		} else {
			// 			app.$app.error('授权失败，请重新授权！');
			// 		}
			// 	}
			// },
			//登录成功后跳转
			onNavigateBack(delta) {
				let to = this.$store.getters.to;
				if (to && to.route) {
					this.$app.redirectTo(to.route, to.param)
				} else {
					this.$app.redirectTo(tabBarPages[0])
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 100rpx 80rpx;
		background: #fff;
		height: 100%;
		position: relative;

		.header {
			display: flex;
			margin: 0 auto;
			justify-content: space-around;
			margin-bottom: 96rpx;

			.header-logo {
				position: relative;
				width: 160rpx;
				height: 132rpx;
			}
		}

		.form-item {
			display: flex;
			padding: 18rpx;
			border-bottom: 1rpx solid #f3f1f2;
			margin-bottom: 25rpx;
			height: 96rpx;

			&--input {
				font-size: $uni-font-size-base;
				letter-spacing: 1rpx;
				flex: 1;
				height: 100%;
			}

			&--parts {
				min-width: 100rpx;
				height: 100%;
			}

			.captcha {
				height: 100%;

				.image {
					display: block;
					width: 192rpx;
					height: 100%;
				}
			}

			.captcha-sms {
				font-size: 22rpx;
				line-height: 50rpx;

				.activate {
					color: #F7441D;
				}

				.un-activate {
					color: #9e9e9e;
				}
			}
		}

		.login-button {
			width: 100%;
			height: 84rpx;
			margin-top: 70rpx;
			background: linear-gradient(118.17deg, #FEA370 0%, #FE2406 95.01%);
			text-align: center;
			line-height: 86rpx;
			color: #fff;
			border-radius: 16rpx;
			box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.1);
			letter-spacing: 5rpx;
		}

		//底部
		.footer {
			text-align: center;
			position: absolute;
			left: 0;
			bottom: 0;
			margin-bottom: 40rpx;

			.other {
				position: relative;
				padding-left: 20rpx;
				padding-right: 20rpx;
				font-size: $uni-font-size-base;
				color: gray;

				&::after {
					display: block;
					content: "";
					width: 60%;
					height: 2rpx;
					background-color: gray;
					position: absolute;
					top: 50%;
					left: -60%;
					transform: translateY(-50%);
				}

				&::before {
					display: block;
					content: "";
					width: 60%;
					height: 2rpx;
					background-color: gray;
					position: absolute;
					top: 50%;
					right: -60%;
					transform: translateY(-50%);
				}
			}

			.login-type {
				display: flex;
				margin: 0 auto;
				justify-content: space-around;
				margin-top: 10rpx;
				margin-bottom: 80rpx;

				.login-weixin {
					position: relative;
					width: 60rpx;
					height: 60rpx;
				}

			}

			.footer-text {
				font-size: $uni-font-size-base;
				color: gray;
				padding-left: 116rpx;
				padding-right: 116rpx;
				padding-bottom: 30rpx;
			}

		}
	}

	.auth-title {
		color: #585858;
		font-size: 34rpx;
		margin-bottom: 40rpx;
	}

	.auth-subtitle {
		color: #888;
		margin-bottom: 88rpx;
		font-size: 28rpx;
	}

	.login-btn {
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			line-height: 88rpx;
			background: #04be01;
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			text-align: center;
		}
	}


	.no-login-btn {
		margin-top: 20rpx;
		padding: 0 20rpx;

		.button {
			height: 88rpx;
			line-height: 88rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			border-radius: 999rpx;
			text-align: center;
		}
	}
</style>